import React, { useState, useEffect, useContext, useRef } from 'react';
import axios from 'axios';
import { Card, Row, Col, Button, Tabs, Spin, message, Modal, Form, Input, Select, Rate, Radio, Table, Tag, Progress, Divider, Checkbox } from 'antd';
import { EditOutlined, RocketOutlined, ExperimentOutlined, ArrowUpOutlined, ArrowDownOutlined, ProjectOutlined } from '@ant-design/icons';
import { API_BASE_URL } from '../config';
import { useSpring, animated } from 'react-spring';
import { RiBrainLine } from 'react-icons/ri';
import { FaBrain, FaRobot, FaNetworkWired } from 'react-icons/fa';
import { GiBrain, GiArtificialIntelligence } from 'react-icons/gi';
import { BiData } from 'react-icons/bi';
import { TbBrain } from 'react-icons/tb';
import { TagCloud } from 'react-tagcloud';
import FeatureDefinition from './FeatureDefinition';
import FeatureMapping from './FeatureMapping';
import TemplateParameterList from './TemplateParameterList';
import ProductParameterList from './ProductParameterList';
import ModelMapping from './ModelMapping';
import ProcessFlowChart from './ProcessFlowChart';
import { TabsContext } from '../contexts/TabsContext';
import Chart from '../utils/chartConfig';

// 动画图标数组，用于随机选择展示
const aiIcons = [
  <FaBrain size={64} />, 
  <FaRobot size={64} />, 
  <FaNetworkWired size={64} />,
  <GiBrain size={64} />, 
  <GiArtificialIntelligence size={64} />, 
  <BiData size={64} />,
  <TbBrain size={64} />,
  <RiBrainLine size={64} />
];

// 模拟数据，用于API调用失败时显示
const mockModels = [
  {
    id: 1,
    code: "V01",
    name: "工艺推荐XGBoost模型",
    model_type: "xgboost",
    algorithm: "gradient_boosting",
    current_version: "1.0",
    create_time: "2025-06-25T16:30:00",
    update_time: "2025-06-25T16:30:00"
  },
  {
    id: 2,
    code: "V02",
    name: "特征匹配神经网络模型",
    model_type: "neural_network",
    algorithm: "deep_learning",
    current_version: "1.2",
    create_time: "2025-06-26T10:15:00",
    update_time: "2025-06-27T14:20:00"
  },
  {
    id: 3,
    code: "V03",
    name: "模板相似度计算模型",
    model_type: "similarity",
    algorithm: "cosine_similarity",
    current_version: "2.0",
    create_time: "2025-06-28T09:45:00",
    update_time: "2025-06-29T11:30:00"
  },
  {
    id: 4,
    code: "V04",
    name: "工艺参数优化模型",
    model_type: "optimization",
    algorithm: "genetic_algorithm",
    current_version: "1.5",
    create_time: "2025-07-01T15:10:00",
    update_time: "2025-07-02T16:25:00"
  }
];

const algorithmOptions = [
  { value: 'xgboost', label: 'XGBoost' },
  { value: 'random_forest', label: 'Random Forest' },
  { value: 'lightgbm', label: 'LightGBM' },
  { value: 'knn', label: 'KNN' }
];

// 算法对应的模型类型映射
const algorithmModelTypeMap = {
  'xgboost': 'xgboost',
  'random_forest': 'random_forest',
  'lightgbm': 'lightgbm',
  'knn': 'knn'
};

// 更新组件定义，接受参数
const IntelligentRecommendation = ({ productId, bomId, productCode, productName, initialActiveTab }) => {
  // 添加日志输出，查看收到的initialActiveTab参数
  console.log('IntelligentRecommendation组件初始化，收到参数 initialActiveTab:', initialActiveTab);
  
  const [models, setModels] = useState([]);
  const [activeTab, setActiveTab] = useState(initialActiveTab || 'models');
  
  // 添加日志输出，确认activeTab的初始状态
  console.log('IntelligentRecommendation组件初始化，activeTab状态设置为:', activeTab);
  
  const [loading, setLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [currentModel, setCurrentModel] = useState(null);
  const [form] = Form.useForm();
  const [trainingModel, setTrainingModel] = useState(null);
  const [trainingModalVisible, setTrainingModalVisible] = useState(false);
  const [modelStatusMap, setModelStatusMap] = useState({}); // 存储模型训练状态
  
  // 添加产品和BOM信息状态
  const [productInfo, setProductInfo] = useState(null);
  const [bomInfo, setBomInfo] = useState(null);
  const [productLoading, setProductLoading] = useState(false);
  
  // 新增推荐相关状态
  const [recommendationLoading, setRecommendationLoading] = useState(false);
  const [recommendations, setRecommendations] = useState(null);
  const [recommendModalVisible, setRecommendModalVisible] = useState(false);
  const [noProductModalVisible, setNoProductModalVisible] = useState(false);
  const [selectedModelForRecommendation, setSelectedModelForRecommendation] = useState(null);
  const [feedbackForm] = Form.useForm();
  const [selectedTemplate, setSelectedTemplate] = useState(null);
  const [logId, setLogId] = useState(null);
  const [feedbackModalVisible, setFeedbackModalVisible] = useState(false);
  
  // 雷达图相关
  const radarChartRef = useRef(null);
  const radarChartInstance = useRef(null);
  
  // 新增图表相关ref
  const gaugeChartRef = useRef(null);
  const gaugeChartInstance = useRef(null);
  const barChartRef = useRef(null);
  const barChartInstance = useRef(null);
  
  // 获取TabsContext以便导航
  const { addTab } = useContext(TabsContext);
  
  // 动画效果
  const fadeAnimation = useSpring({
    from: { opacity: 0, transform: 'translateY(20px)' },
    to: { opacity: 1, transform: 'translateY(0)' },
    delay: 200,
  });
  
  // 添加流程图相关状态
  const [flowChartVisible, setFlowChartVisible] = useState(false);
  const [selectedTemplateId, setSelectedTemplateId] = useState(null);
  
  // 在组件内部添加检测移动设备的状态
  const [isMobile, setIsMobile] = useState(false);
  
  // 在组件内部添加新的状态来跟踪是否需要创建工艺
  const [createProcess, setCreateProcess] = useState(true);
  
  useEffect(() => {
    fetchModels();
    
    // 如果有产品ID和BOM ID，获取相关信息
    if (productId) {
      fetchProductInfo(productId);
    }
    if (bomId) {
      fetchBomInfo(bomId);
    }
  }, [productId, bomId]);
  
  useEffect(() => {
    // 获取所有模型的训练状态
    if (models && models.length > 0) {
      models.forEach(model => {
        fetchModelStatus(model.id);
      });
    }
  }, [models]);
  
  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);
  
  const fetchModels = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/recommendation_model`);
      if (response.data && response.data.code === 200) {
        setModels(response.data.data.items);
      } else {
        message.error('获取推荐模型列表失败，显示模拟数据');
        setModels(mockModels); // 使用模拟数据
      }
    } catch (error) {
      console.error('获取推荐模型列表出错:', error);
      message.error('获取推荐模型列表出错，显示模拟数据');
      setModels(mockModels); // 使用模拟数据
    } finally {
      setLoading(false);
    }
  };
  
  // 获取模型训练状态
  const fetchModelStatus = async (modelId) => {
    try {
      const response = await axios.get(`${API_BASE_URL}/api/recommendation_model/${modelId}/status`);
      if (response.data && response.data.code === 200) {
        setModelStatusMap(prev => ({
          ...prev,
          [modelId]: response.data.data
        }));
      }
    } catch (error) {
      console.error(`获取模型 ${modelId} 的训练状态出错:`, error);
    }
  };
  
  // 获取产品信息
  const fetchProductInfo = async (id) => {
    setProductLoading(true);
    try {
      console.log('获取产品信息，ID:', id);
      const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
      if (response.data && response.data.code === 200) {
        console.log('获取到产品信息:', response.data.data);
        setProductInfo(response.data.data);
      } else {
        message.error('获取产品信息失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品信息出错:', error);
      message.error('获取产品信息出错: ' + (error.message || '未知错误'));
    } finally {
      setProductLoading(false);
    }
  };
  
  // 获取BOM信息
  const fetchBomInfo = async (id) => {
    try {
      console.log('获取BOM信息，ID:', id);
      const response = await axios.get(`${API_BASE_URL}/api/product_bom/${id}`);
      if (response.data && response.data.code === 200) {
        console.log('获取到BOM信息:', response.data.data);
        setBomInfo(response.data.data);
      } else {
        message.error('获取BOM信息失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取BOM信息出错:', error);
      message.error('获取BOM信息出错: ' + (error.message || '未知错误'));
    }
  };
  
  // 随机获取一个AI图标
  const getRandomIcon = () => {
    const randomIndex = Math.floor(Math.random() * aiIcons.length);
    return aiIcons[randomIndex];
  };
  
  // 时间格式化函数
  const formatDateTime = (dateString) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };
  
  // 处理编辑按钮点击
  const handleEdit = (model) => {
    setCurrentModel(model);
    form.setFieldsValue({
      name: model.name,
      algorithm: model.algorithm === 'gradient_boosting' ? 'xgboost' : 
                 model.algorithm === 'deep_learning' ? 'knn' : model.model_type,
    });
    setEditModalVisible(true);
  };
  
  // 处理训练按钮点击
  const handleTrain = (model) => {
    setTrainingModel(model);
    setTrainingModalVisible(true);
  };
  
  // 处理推荐按钮点击
  const handleRecommend = (model) => {
    setSelectedModelForRecommendation(model);
    
    // 检查是否有产品ID
    if (!productId) {
      console.log('未选择产品，无法进行推荐');
      setNoProductModalVisible(true);
      return;
    }
    
    // 有产品ID，开始推荐流程
    fetchRecommendations(model.id);
  };
  
  // 获取推荐结果
  const fetchRecommendations = async (modelId) => {
    setRecommendationLoading(true);
    try {
      console.log(`开始获取推荐结果，产品ID: ${productId}, 模型ID: ${modelId}`);
      
      const response = await axios.post(`${API_BASE_URL}/api/recommendation/recommend_templates`, {
        product_id: productId,
        model_id: modelId,
        max_results: 3
      });
      
      if (response.data && response.data.code === 200) {
        console.log('获取到推荐结果:', response.data.data);
        setRecommendations(response.data.data);
        setLogId(response.data.data.log_id);
        
        // 设置初始选中的模板为第一个推荐结果
        if (response.data.data.recommendations && response.data.data.recommendations.length > 0) {
          setSelectedTemplate(response.data.data.recommendations[0]);
        }
        
        setRecommendModalVisible(true);
        
        // 下一帧渲染所有图表
        setTimeout(() => {
          renderRadarChart(response.data.data.radar_chart_data);
          
          // 如果有推荐结果，渲染第一个推荐的仪表盘和条形图
          if (response.data.data.recommendations && response.data.data.recommendations.length > 0) {
            renderGaugeChart(response.data.data.recommendations[0]);
            renderBarChart(response.data.data.recommendations[0]);
          }
        }, 100);
      } else {
        message.error('获取推荐结果失败: ' + (response.data?.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取推荐结果出错:', error);
      message.error('获取推荐结果出错: ' + (error.message || '未知错误'));
    } finally {
      setRecommendationLoading(false);
    }
  };
  
  // 渲染雷达图
  const renderRadarChart = (radarData) => {
    if (!radarData || !radarChartRef.current) return;
    
    // 如果已有图表实例，销毁它
    if (radarChartInstance.current) {
      radarChartInstance.current.destroy();
    }
    
    const ctx = radarChartRef.current.getContext('2d');
    
    const datasets = [];
    const dimensions = radarData.dimensions;
    
    // 为每个模板创建数据集
    for (const [key, values] of Object.entries(radarData.template_values)) {
      const templateId = key.split('_')[1];
      
      // 生成不同的颜色
      const r = Math.floor(50 + Math.random() * 150);
      const g = Math.floor(50 + Math.random() * 150);
      const b = Math.floor(50 + Math.random() * 150);
      
      datasets.push({
        label: `模板${templateId}`,
        data: values,
        fill: true,
        backgroundColor: `rgba(${r}, ${g}, ${b}, 0.2)`,
        borderColor: `rgba(${r}, ${g}, ${b}, 1)`,
        pointBackgroundColor: `rgba(${r}, ${g}, ${b}, 1)`,
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: `rgba(${r}, ${g}, ${b}, 1)`
      });
    }
    
    radarChartInstance.current = new Chart(ctx, {
      type: 'radar',
      data: {
        labels: dimensions,
        datasets: datasets
      },
      options: {
        elements: {
          line: {
            borderWidth: 3
          }
        },
        scales: {
          r: {
            angleLines: {
              display: true
            },
            suggestedMin: 0,
            suggestedMax: 1,
            ticks: {
              stepSize: 0.2
            }
          }
        },
        plugins: {
          legend: {
            position: 'top',
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                const label = context.dataset.label || '';
                const value = context.parsed.r;
                return `${label}: ${(value * 100).toFixed(0)}%`;
              }
            }
          }
        }
      }
    });
  };
  
  // 渲染仪表盘图表
  const renderGaugeChart = (template) => {
    if (!gaugeChartRef.current || !template) return;
    
    // 如果已有图表实例，销毁它
    if (gaugeChartInstance.current) {
      gaugeChartInstance.current.destroy();
    }
    
    const ctx = gaugeChartRef.current.getContext('2d');
    const score = template.similarity_score * 100;
    
    // 根据匹配度确定颜色
    let color = '#f5222d'; // 默认红色 (低匹配度)
    if (score >= 75) {
      color = '#52c41a'; // 绿色 (高匹配度)
    } else if (score >= 50) {
      color = '#faad14'; // 黄色 (中等匹配度)
    }
    
    gaugeChartInstance.current = new Chart(ctx, {
      type: 'doughnut',
      data: {
        datasets: [{
          data: [score, 100 - score],
          backgroundColor: [color, '#f0f0f0'],
          circumference: 180,
          rotation: -90,
          borderWidth: 0
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '70%',
        plugins: {
          tooltip: {
            enabled: false
          },
          legend: {
            display: false
          }
        }
      }
    });
    
    // 添加中心文本
    setTimeout(() => {
      const centerX = gaugeChartInstance.current.chartArea.width / 2;
      const centerY = gaugeChartInstance.current.chartArea.height / 2;
      
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.font = 'bold 24px Arial';
      ctx.fillStyle = color;
      ctx.fillText(`${score.toFixed(1)}%`, centerX, centerY);
      
      ctx.font = '14px Arial';
      ctx.fillStyle = '#666';
      ctx.fillText('匹配度', centerX, centerY + 30);
    }, 50);
  };
  
  // 渲染条形图(关键差异图)
  const renderBarChart = (template) => {
    if (!barChartRef.current || !template || !template.details || !template.details.feature_matches) return;
    
    // 如果已有图表实例，销毁它
    if (barChartInstance.current) {
      barChartInstance.current.destroy();
    }
    
    // 筛选匹配度较低的特征(小于50%)进行展示，最多显示5个
    const lowMatchFeatures = template.details.feature_matches
      .filter(match => match.match_score < 0.5)
      .sort((a, b) => a.match_score - b.match_score)
      .slice(0, 5);
    
    if (lowMatchFeatures.length === 0) {
      // 如果没有低匹配度特征，显示最不匹配的前5个特征
      lowMatchFeatures.push(...template.details.feature_matches
        .sort((a, b) => a.match_score - b.match_score)
        .slice(0, 5));
    }
    
    const ctx = barChartRef.current.getContext('2d');
    
    const featureNames = lowMatchFeatures.map(item => item.feature_name);
    const productValues = lowMatchFeatures.map(item => {
      // 尝试转换为数字，如果不是数字则返回0.5作为占位
      const numValue = Number(item.product_value);
      return isNaN(numValue) ? 0.5 : numValue;
    });
    const templateValues = lowMatchFeatures.map(item => {
      const numValue = Number(item.template_value);
      return isNaN(numValue) ? 0.5 : numValue;
    });
    const matchScores = lowMatchFeatures.map(item => item.match_score);
    
    barChartInstance.current = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: featureNames,
        datasets: [
          {
            label: '产品值',
            data: productValues,
            backgroundColor: 'rgba(24, 144, 255, 0.7)',
            borderColor: 'rgba(24, 144, 255, 1)',
            borderWidth: 1
          },
          {
            label: '模板值',
            data: templateValues,
            backgroundColor: 'rgba(250, 173, 20, 0.7)',
            borderColor: 'rgba(250, 173, 20, 1)',
            borderWidth: 1
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: true
          }
        },
        plugins: {
          legend: {
            position: 'top',
          },
          tooltip: {
            callbacks: {
              afterBody: function(context) {
                const index = context[0].dataIndex;
                return `匹配度: ${(matchScores[index] * 100).toFixed(0)}%`;
              }
            }
          }
        }
      }
    });
  };
  
  // 处理模板选择
  const handleSelectTemplate = (template) => {
    setSelectedTemplate(template);
    
    // 更新图表以显示选择的模板数据
    setTimeout(() => {
      renderGaugeChart(template);
      renderBarChart(template);
    }, 50);
    
    setFeedbackModalVisible(true);
  };
  
  // 处理打开流程图
  const handleOpenFlowChart = (templateId) => {
    setSelectedTemplateId(templateId);
    setFlowChartVisible(true);
  };
  
  // 处理关闭流程图
  const handleCloseFlowChart = () => {
    setFlowChartVisible(false);
  };
  
  // 创建产品工艺路线
  const createProductProcessRoute = async (templateId) => {
    if (!productId || !templateId) {
      message.error('缺少产品ID或模板ID');
      return null;
    }
    
    try {
      // 显示加载状态
      const hide = message.loading('正在创建工艺路线...', 0);
      
      // 1. 获取产品信息
      const productResponse = await axios.get(`${API_BASE_URL}/api/product_info/${productId}`);
      if (!productResponse.data || productResponse.data.code !== 200) {
        hide();
        message.error('获取产品信息失败');
        return null;
      }
      
      const productData = productResponse.data.data;
      
      // 2. 获取模板详情
      const templateResponse = await axios.get(`${API_BASE_URL}/api/process_template_info/${templateId}`);
      if (!templateResponse.data || templateResponse.data.code !== 200) {
        hide();
        message.error('获取模板详情失败');
        return null;
      }
      
      const templateData = templateResponse.data.data;
      
      // 3. 生成工艺路线编码（产品编码+3位流水码）
      // 需要获取当前产品的工艺路线列表，确定流水码
      const routesResponse = await axios.get(`${API_BASE_URL}/api/product_process_route?product_id=${productId}`);
      let sequenceNumber = 1;
      
      if (routesResponse.data && routesResponse.data.code === 200 && routesResponse.data.data.items.length > 0) {
        // 找出最大的流水码并加1
        const routes = routesResponse.data.data.items;
        const sequenceNumbers = routes.map(route => {
          const code = route.code || '';
          const sequence = code.substring(productData.code.length);
          return parseInt(sequence, 10) || 0;
        });
        
        sequenceNumber = Math.max(...sequenceNumbers, 0) + 1;
      }
      
      // 生成3位流水码（不足3位前面补0）
      const sequenceCode = String(sequenceNumber).padStart(3, '0');
      const routeCode = `${productData.code}${sequenceCode}`;
      
      // 4. 创建工艺路线基本信息
      const routeData = {
        code: routeCode,
        name: `${productData.name}工艺路线`,
        product_id: productId,
        product_version_id: productData.version_id || 1,
        template_id: templateId,
        status: "草稿",
        description: `基于工艺模板"${templateData.name}"创建`,
        flow_chart: templateData.flow_chart || "{}"
      };
      
      // 5. 调用API创建工艺路线
      const createRouteResponse = await axios.post(`${API_BASE_URL}/api/product_process_route`, routeData);
      
      if (!createRouteResponse.data || createRouteResponse.data.code !== 201) {
        hide();
        message.error('创建工艺路线失败');
        return null;
      }
      
      const routeId = createRouteResponse.data.data.id;
      
      // 6. 获取模板下的工序列表
      const operationsResponse = await axios.get(`${API_BASE_URL}/api/process_template_operation?template_id=${templateId}`);
      
      if (operationsResponse.data && operationsResponse.data.code === 200) {
        const operations = operationsResponse.data.data.items || [];
        
        // 7. 为每个工序创建对应的产品工艺工序
        for (let i = 0; i < operations.length; i++) {
          const templateOp = operations[i];
          
          // 生成工序编码（工艺路线编码+3位流水码）
          const opSequenceCode = String(i + 1).padStart(3, '0');
          const operationCode = `${routeCode}${opSequenceCode}`;
          
          // 创建工序数据
          const operationData = {
            code: operationCode,
            name: templateOp.name,
            route_id: routeId,
            sequence: i + 1,
            work_hour: templateOp.work_hour || 0,
            description: templateOp.description || ''
          };
          
          // 调用API创建工序
          const createOpResponse = await axios.post(`${API_BASE_URL}/api/product_process_operation`, operationData);
          
          if (!createOpResponse.data || createOpResponse.data.code !== 201) {
            console.error('创建工序失败:', templateOp.name);
            continue;
          }
          
          const operationId = createOpResponse.data.data.id;
          
          // 8. 获取模板工序下的工步列表
          const stepsResponse = await axios.get(`${API_BASE_URL}/api/process_template_step?operation_id=${templateOp.id}`);
          
          if (stepsResponse.data && stepsResponse.data.code === 200) {
            const steps = stepsResponse.data.data.items || [];
            
            // 9. 为每个工步创建对应的产品工艺工步
            for (let j = 0; j < steps.length; j++) {
              const templateStep = steps[j];
              
              // 生成工步编码（工序编码+3位流水码）
              const stepSequenceCode = String(j + 1).padStart(3, '0');
              const stepCode = `${operationCode}${stepSequenceCode}`;
              
              // 创建工步数据
              const stepData = {
                code: stepCode,
                name: templateStep.name,
                operation_id: operationId,
                sequence: j + 1,
                work_hour: templateStep.work_hour || 0,
                description: templateStep.description || ''
              };
              
              // 调用API创建工步
              await axios.post(`${API_BASE_URL}/api/product_process_step`, stepData);
            }
          }
        }
      }
      
      hide();
      message.success('工艺路线创建成功');
      
      // 返回创建的工艺路线ID和代码
      return {
        id: routeId,
        code: routeCode,
        name: routeData.name
      };
    } catch (error) {
      console.error('创建工艺路线出错:', error);
      message.error('创建工艺路线出错: ' + (error.message || '未知错误'));
      return null;
    }
  };
  
  // 修改handleSubmitFeedback函数，根据createProcess进行相应操作
  const handleSubmitFeedback = async (values) => {
    if (!logId || !selectedTemplate) {
      message.error('反馈信息不完整');
      return;
    }
    
    try {
      console.log('提交反馈，数据:', {
        selected_template_id: selectedTemplate.template_id,
        score: values.score,
        feedback: values.feedback,
        usefulness: values.usefulness,
        create_process: values.create_process // 添加是否创建工艺的选项
      });
      
      // 根据API文档，创建符合预期的请求体
      // 参考"智能推荐接口.md"中的recommendation_log创建接口
      // 包含创建接口中所有的字段
      const requestBody = {
        product_id: productId,
        model_id: selectedModelForRecommendation?.id,
        recommended_templates: recommendations?.recommendations ? 
          JSON.stringify(recommendations.recommendations.map(r => r.template_id)) : 
          JSON.stringify([selectedTemplate.template_id]),
        selected_template_id: selectedTemplate.template_id,
        score: values.score || 5, // 默认值为5
        feedback: values.feedback || '',
        create_user: "user" // 添加用户标识
      };
      
      // 如果有usefulness字段，添加到feedback中
      if (values.usefulness) {
        requestBody.feedback = `${values.usefulness}: ${requestBody.feedback}`;
      }
      
      console.log('发送请求体:', requestBody);
      
      // 移除可能导致问题的undefined值
      Object.keys(requestBody).forEach(key => {
        if (requestBody[key] === undefined) {
          delete requestBody[key];
        }
      });
      
      const response = await axios.put(`${API_BASE_URL}/api/recommendation_log/${logId}`, requestBody);
      
      if (response.data && response.data.code === 200) {
        message.success('反馈提交成功');
        setFeedbackModalVisible(false);
        
        // 如果用户选择创建工艺，创建产品工艺路线
        if (values.create_process) {
          // 创建产品工艺路线
          const routeResult = await createProductProcessRoute(selectedTemplate.template_id);
          
          if (routeResult) {
            // 打开产品工艺页面
            const tabKey = `productProcess-${routeResult.id}`;
            const tabTitle = `${routeResult.code}工艺`;
            addTab(tabKey, tabTitle, 'ProcessDetail', { routeId: routeResult.id });
          }
        } else {
          // 询问是否要打开选择的模板
          Modal.confirm({
            title: '操作成功',
            content: '是否要打开选择的工艺模板？',
            okText: '打开模板',
            cancelText: '稍后再说',
            onOk: () => {
              // 打开工艺模板页面的代码
              const tabKey = `templateDetail-${selectedTemplate.template_id}`;
              const tabTitle = `${selectedTemplate.template_name || '工艺模板'} ${selectedTemplate.template_version || ''}`;
              addTab(tabKey, tabTitle, 'ProcessTemplateDetail', { templateId: selectedTemplate.template_id });
            }
          });
        }
      } else {
        message.error('提交反馈失败: ' + (response.data?.message || '未知错误'));
      }
    } catch (error) {
      console.error('提交反馈出错:', error);
      
      // 详细记录错误信息
      if (error.response) {
        console.error('错误状态码:', error.response.status);
        console.error('错误详情:', error.response.data);
        
        // 如果有详细的验证错误信息，显示给用户
        if (error.response.data && error.response.data.detail) {
          if (Array.isArray(error.response.data.detail)) {
            error.response.data.detail.forEach((item, index) => {
              console.error(`验证错误 ${index + 1}:`, item);
              message.error(`验证错误: ${JSON.stringify(item)}`);
            });
          } else {
            console.error('验证错误:', error.response.data.detail);
            message.error(`验证错误: ${error.response.data.detail}`);
          }
        }
      }
      
      message.error('提交反馈出错: ' + (error.message || '未知错误'));
    }
  };
  
  // 处理导航到产品库
  const navigateToProductLibrary = () => {
    setNoProductModalVisible(false);
    addTab('productLibrary', '产品库', 'ProductLibrary');
  };
  
  // 执行模型训练
  const trainModel = async () => {
    if (!trainingModel) return;
    
    setTrainingModalVisible(false);
    const hide = message.loading('正在训练模型...', 0);
    
    try {
      // 将产品和BOM信息添加到训练请求中
      const trainingData = {
        model_id: trainingModel.id,
        product_id: productId,
        bom_id: bomId
      };
      
      // 从模型中获取算法，或使用合适的映射将model.algorithm映射为API支持的算法值
      let algorithmParam = trainingModel.model_type;
      
      // 如果模型类型是gradient_boosting，使用xgboost
      if (trainingModel.algorithm === 'gradient_boosting') {
        algorithmParam = 'xgboost';
      } 
      // 如果模型类型是deep_learning，使用knn
      else if (trainingModel.algorithm === 'deep_learning') {
        algorithmParam = 'knn';
      }
      // 确保算法参数是API支持的值之一
      else if (!['xgboost', 'random_forest', 'lightgbm', 'knn'].includes(algorithmParam)) {
        algorithmParam = 'xgboost'; // 默认使用xgboost
      }
      
      console.log('开始训练模型，请求数据:', trainingData);
      console.log(`使用算法 ${algorithmParam} 训练模型`);
      
      const response = await axios.post(
        `${API_BASE_URL}/api/recommendation_model/${trainingModel.id}/train?algorithm=${algorithmParam}`, 
        trainingData
      );
      
      if (response.data && response.data.code === 200) {
        hide();
        message.success('模型训练任务已提交');
        // 更新模型状态
        fetchModelStatus(trainingModel.id);
      } else {
        hide();
        message.error('提交模型训练失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      hide();
      console.error('模型训练出错:', error);
      message.error('模型训练出错: ' + (error.message || '未知错误'));
    }
  };
  
  // 保存编辑的模型
  const handleSaveEdit = async () => {
    try {
      const values = await form.validateFields();
      
      if (!currentModel) return;
      
      // 更新版本号，V+2位流水，流水自动加1
      const currentVersion = currentModel.current_version || "V00";
      const versionNumber = parseInt(currentVersion.substring(1), 10) || 0;
      const newVersion = `V${String(versionNumber + 1).padStart(2, '0')}`;
      
      // 根据算法自动更新模型类型
      const modelType = algorithmModelTypeMap[values.algorithm] || values.algorithm;
      
      const updatedModel = {
        name: values.name,
        algorithm: values.algorithm,
        model_type: modelType,
        current_version: newVersion
      };
      
      const hide = message.loading('正在更新模型...', 0);
      
      try {
        const response = await axios.put(`${API_BASE_URL}/api/recommendation_model/${currentModel.id}`, updatedModel);
        
        hide();
        if (response.data && response.data.code === 200) {
          message.success('模型更新成功');
          setEditModalVisible(false);
          fetchModels(); // 刷新模型列表
          
          // 提示用户重新训练模型
          Modal.confirm({
            title: '模型已更新',
            content: '模型信息已更新，是否立即训练该模型？',
            okText: '立即训练',
            cancelText: '稍后训练',
            onOk: () => {
              // 获取更新后的模型信息
              const updatedModelData = {
                ...currentModel,
                ...updatedModel
              };
              handleTrain(updatedModelData);
            }
          });
        } else {
          message.error('模型更新失败：' + (response.data?.message || '未知错误'));
        }
      } catch (error) {
        hide();
        console.error('更新模型出错:', error);
        message.error('更新模型出错：' + (error.response?.data?.message || error.message || '未知错误'));
      }
    } catch (validateError) {
      console.error('表单验证失败:', validateError);
    }
  };
  
  // 渲染模型卡片
  const renderModelCards = () => {
    if (loading) {
      return (
        <div className="loading-container">
          <Spin size="large" />
          <p>正在加载模型列表...</p>
        </div>
      );
    }
    
    if (!models || models.length === 0) {
      return (
        <div className="empty-data">
          <p>暂无模型数据</p>
          <Button type="primary" onClick={fetchModels}>刷新</Button>
        </div>
      );
    }
    
    return (
      <Row gutter={[24, 24]}>
        {models.map((model) => {
          // 每个模型卡片使用固定的图标
          const ModelIcon = aiIcons[model.id % aiIcons.length];
          const modelStatus = modelStatusMap[model.id] || {};
          
          return (
            <Col xs={24} sm={12} md={12} lg={8} xl={8} key={model.id}>
              <animated.div style={fadeAnimation}>
                <Card
                  hoverable
                  className="model-card"
                  actions={[
                    <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(model)}>编辑</Button>,
                    <Button type="link" icon={<ExperimentOutlined />} onClick={() => handleTrain(model)}>训练</Button>,
                    <Button type="link" icon={<RocketOutlined />} onClick={() => handleRecommend(model)}>推荐</Button>
                  ]}
                >
                  <div className="model-card-content">
                    <div className="model-card-icon">
                      {React.cloneElement(ModelIcon, { 
                        className: 'pulsing-icon',
                        style: { width: '50%', height: '50%' }
                      })}
                    </div>
                    <div className="model-card-info">
                      <div className="info-item">
                        <span className="info-label">编码:</span>
                        <span className="info-value">{model.code || '-'}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">名称:</span>
                        <span className="info-value">{model.name || '-'}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">版本:</span>
                        <span className="info-value">{model.current_version || '-'}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">算法:</span>
                        <span className="info-value">{model.algorithm || '-'}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">模型类型:</span>
                        <span className="info-value">{model.model_type || '-'}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">创建时间:</span>
                        <span className="info-value">{formatDateTime(model.create_time)}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">更新时间:</span>
                        <span className="info-value">{formatDateTime(model.update_time)}</span>
                      </div>
                      <div className="info-item">
                        <span className="info-label">训练时间:</span>
                        <span className="info-value">{modelStatus.trained ? formatDateTime(modelStatus.trained_at) : '未训练'}</span>
                      </div>
                    </div>
                  </div>
                </Card>
              </animated.div>
            </Col>
          );
        })}
      </Row>
    );
  };
  
  // 替换原来的特征列表功能开发中内容
  const renderContent = () => {
    if (activeTab === 'models') {
      return renderModelCards();
    } else if (activeTab === 'features') {
      return <FeatureDefinition />;
    } else if (activeTab === 'mappings') {
      return <FeatureMapping />;
    } else if (activeTab === 'template_parameters') {
      return <TemplateParameterList />;
    } else if (activeTab === 'product_parameters') {
      return <ProductParameterList />;
    } else if (activeTab === 'model_mappings') {
      return <ModelMapping />;
    }
    return null;
  };
  
  return (
    <div className="intelligent-recommendation">
      <div className="page-header">
        <div className="tab-container">
          <div className="tabs">
            <div 
              className={`tab-item ${activeTab === 'models' ? 'active' : ''}`}
              onClick={() => setActiveTab('models')}
            >
              模型列表
            </div>
            <div 
              className={`tab-item ${activeTab === 'features' ? 'active' : ''}`}
              onClick={() => setActiveTab('features')}
            >
              特征列表
            </div>
            <div 
              className={`tab-item ${activeTab === 'mappings' ? 'active' : ''}`}
              onClick={() => setActiveTab('mappings')}
            >
              特征映射
            </div>
            <div 
              className={`tab-item ${activeTab === 'template_parameters' ? 'active' : ''}`}
              onClick={() => setActiveTab('template_parameters')}
            >
              模板参数
            </div>
            <div 
              className={`tab-item ${activeTab === 'product_parameters' ? 'active' : ''}`}
              onClick={() => setActiveTab('product_parameters')}
            >
              产品参数
            </div>
            <div 
              className={`tab-item ${activeTab === 'model_mappings' ? 'active' : ''}`}
              onClick={() => setActiveTab('model_mappings')}
            >
              模型映射
            </div>
          </div>
        </div>
      </div>
      
      <div className="content-body">
        {renderContent()}
      </div>
      
      {/* 编辑模型对话框 */}
      <Modal
        title="编辑模型"
        open={editModalVisible}
        onOk={handleSaveEdit}
        onCancel={() => setEditModalVisible(false)}
        maskClosable={false}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="模型名称"
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input placeholder="请输入模型名称" />
          </Form.Item>
          
          <Form.Item
            name="algorithm"
            label="算法"
            rules={[{ required: true, message: '请选择算法' }]}
          >
            <Select placeholder="请选择算法" options={algorithmOptions} />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 训练模型确认对话框 */}
      <Modal
        title="训练模型"
        open={trainingModalVisible}
        onOk={trainModel}
        onCancel={() => setTrainingModalVisible(false)}
        maskClosable={false}
        okText="确认训练"
        cancelText="取消"
      >
        <p>请确认已完成特征同步和正确建立特征映射，然后再进行模型训练。</p>
        <p>训练过程可能需要一些时间，请耐心等待。</p>
      </Modal>
      
      {/* 无产品提示对话框 */}
      <Modal
        title="提示"
        open={noProductModalVisible}
        onOk={navigateToProductLibrary}
        onCancel={() => setNoProductModalVisible(false)}
        okText="前往产品库"
        cancelText="取消"
      >
        <p>请先选择需要创建工艺路线的产品</p>
      </Modal>
      
      {/* 推荐结果对话框 */}
      <Modal
        title="工艺模板推荐结果"
        open={recommendModalVisible}
        onCancel={() => {
          setRecommendModalVisible(false);
          setSelectedTemplate(null);
        }}
        footer={null}
        width={isMobile ? "95%" : 1000}
        maskClosable={false}
        styles={{ body: { padding: isMobile ? '12px' : '24px' } }}
      >
        {recommendationLoading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
            <p style={{ marginTop: '16px' }}>正在分析产品特征并生成推荐...</p>
          </div>
        ) : recommendations ? (
          <div>
            {recommendations.recommendations && recommendations.recommendations.length > 0 && (
              <div className="recommendation-visualization">
                {/* 顶部：仪表盘（整体得分） */}
                <div className="gauge-section">
                  <div className="section-title">整体匹配度</div>
                  <div className="gauge-container">
                    <canvas ref={gaugeChartRef} height="150"></canvas>
                  </div>
                </div>
                
                {/* 推荐工艺模板选择 - 移动到这里 */}
                <div className="template-selection-section">
                  <div className="section-title">推荐工艺模板</div>
                  <p className="template-hint">点击模板卡片查看详细数据，点击"选择"按钮提交反馈并使用此模板</p>
                  <Row gutter={[16, 16]}>
                    {recommendations.recommendations.map((template, index) => (
                      <Col xs={24} sm={24} md={12} lg={8} key={index}>
                        <Card 
                          className={selectedTemplate?.template_id === template.template_id ? 'template-card-selected' : 'template-card'}
                          onClick={() => {
                            // 更新选中模板状态和图表，但不打开反馈模态框
                            setSelectedTemplate(template);
                            setTimeout(() => {
                              renderGaugeChart(template);
                              renderBarChart(template);
                            }, 50);
                          }}
                          hoverable
                        >
                          <div className="template-card-header">
                            <div className="template-card-title">
                              推荐 #{index + 1}: {template.template_name}
                            </div>
                            <div className="template-card-actions">
                              <Button 
                                icon={<ProjectOutlined />} 
                                size={isMobile ? "small" : "middle"} 
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleOpenFlowChart(template.template_id);
                                }}
                              >
                                {isMobile ? "" : "工艺流程图"}
                              </Button>
                              <Button 
                                type="primary" 
                                size={isMobile ? "small" : "middle"} 
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleSelectTemplate(template);
                                }}
                              >
                                选择
                              </Button>
                            </div>
                          </div>
                          <div className="template-card-content">
                            <div className="template-card-item">
                              <span className="template-card-label">版本:</span>
                              <span className="template-card-value">{template.template_version}</span>
                            </div>
                            <div className="template-card-item">
                              <span className="template-card-label">匹配度:</span>
                              <span className="template-card-value">{(template.similarity_score * 100).toFixed(2)}%</span>
                            </div>
                            <div className="template-card-item">
                              <span className="template-card-label">特征匹配:</span>
                              <span className="template-card-value">{template.details?.feature_matches.length || 0}项</span>
                            </div>
                          </div>
                        </Card>
                      </Col>
                    ))}
                  </Row>
                </div>
                
                <Divider />
                
                {/* 中部：雷达图（左） + 条形图（右） */}
                <Row gutter={16} className="chart-section">
                  <Col xs={24} sm={24} md={12} lg={12}>
                    <div className="section-title">特征匹配对比雷达图</div>
                    <div className="radar-container">
                      <canvas ref={radarChartRef}></canvas>
                    </div>
                  </Col>
                  <Col xs={24} sm={24} md={12} lg={12}>
                    <div className="section-title">关键差异条形图</div>
                    <div className="bar-container">
                      <canvas ref={barChartRef} height={isMobile ? "250" : "300"}></canvas>
                    </div>
                  </Col>
                </Row>
                
                <Divider />
                
                {/* 底部：标签云（高匹配项）+ 表格（详细数据） */}
                <div className="bottom-section">
                  <Row gutter={16}>
                    <Col span={24}>
                      <div className="section-title">高匹配特征</div>
                      <div className="tag-cloud">
                        {(selectedTemplate || recommendations.recommendations[0]).details?.feature_matches
                          ?.filter(match => match.match_score >= 0.95)
                          .map((match, index) => (
                            <Tag 
                              key={index} 
                              color="green"
                              style={{ margin: '4px', fontSize: '14px', padding: '4px 8px' }}
                            >
                              {match.feature_name}: {match.product_value}
                            </Tag>
                          ))
                        }
                        {(selectedTemplate || recommendations.recommendations[0]).details?.feature_matches
                          ?.filter(match => match.match_score >= 0.95).length === 0 && (
                          <div style={{padding: '16px'}}>暂无完全匹配的特征</div>
                        )}
                      </div>
                    </Col>
                  </Row>
                  
                  <Row style={{ marginTop: '20px' }}>
                    <Col span={24}>
                      <div className="section-title">特征匹配详情表</div>
                      <Table 
                        dataSource={
                          (selectedTemplate || recommendations.recommendations[0]).details?.feature_matches.map((item, index) => ({
                            key: index,
                            feature_name: item.feature_name,
                            product_value: item.product_value,
                            template_value: item.template_value,
                            match_score: item.match_score
                          }))
                        }
                        columns={[
                          {
                            title: '特征名称',
                            dataIndex: 'feature_name',
                            key: 'feature_name',
                          },
                          {
                            title: '产品值',
                            dataIndex: 'product_value',
                            key: 'product_value',
                          },
                          {
                            title: '模板值',
                            dataIndex: 'template_value',
                            key: 'template_value',
                          },
                          {
                            title: '匹配度',
                            dataIndex: 'match_score',
                            key: 'match_score',
                            render: (score) => (
                              <div>
                                <Progress 
                                  percent={Math.round(score * 100)} 
                                  size="small" 
                                  status={
                                    score >= 0.75 ? "success" : 
                                    score >= 0.5 ? "normal" : "exception"
                                  }
                                />
                              </div>
                            ),
                            sorter: (a, b) => a.match_score - b.match_score
                          },
                          {
                            title: '差异',
                            key: 'difference',
                            render: (_, record) => {
                              // 尝试计算数值差异
                              const productVal = Number(record.product_value);
                              const templateVal = Number(record.template_value);
                              if (!isNaN(productVal) && !isNaN(templateVal)) {
                                const diff = ((productVal - templateVal) / templateVal * 100).toFixed(1);
                                return (
                                  <span style={{ color: diff > 0 ? '#f5222d' : '#52c41a' }}>
                                    {diff > 0 ? <ArrowUpOutlined /> : <ArrowDownOutlined />}
                                    {Math.abs(diff)}%
                                  </span>
                                );
                              }
                              return '非数值特征';
                            }
                          }
                        ]}
                        pagination={false}
                        size="small"
                        scroll={{ y: 300 }}
                      />
                    </Col>
                  </Row>
                </div>
              </div>
            )}
            
            {(!recommendations.recommendations || recommendations.recommendations.length === 0) && (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <p>未找到匹配的工艺模板推荐</p>
              </div>
            )}
          </div>
        ) : (
          <div>未获取到推荐数据</div>
        )}
      </Modal>
      
      {/* 反馈表单对话框 */}
      <Modal
        title="提交反馈"
        open={feedbackModalVisible}
        onOk={() => feedbackForm.submit()}
        onCancel={() => setFeedbackModalVisible(false)}
        okText={createProcess ? "提交反馈并创建工艺" : "仅提交反馈"}
        cancelText="取消"
      >
        <Form 
          form={feedbackForm} 
          layout="vertical"
          onFinish={handleSubmitFeedback}
          onValuesChange={(changedValues) => {
            if ('create_process' in changedValues) {
              setCreateProcess(changedValues.create_process);
            }
          }}
          initialValues={{
            create_process: true
          }}
        >
          <Form.Item 
            name="score" 
            label="请为推荐结果评分" 
            rules={[{ required: true, message: '请评分' }]}
          >
            <Rate allowHalf />
          </Form.Item>
          
          <Form.Item 
            name="usefulness" 
            label="推荐结果对您有用吗？"
            rules={[{ required: true, message: '请选择' }]}
          >
            <Radio.Group>
              <Radio value="very">非常有用</Radio>
              <Radio value="somewhat">有一些帮助</Radio>
              <Radio value="little">帮助不大</Radio>
              <Radio value="no">完全没用</Radio>
            </Radio.Group>
          </Form.Item>
          
          <Form.Item 
            name="feedback" 
            label="反馈意见"
          >
            <Input.TextArea placeholder="请输入您对推荐结果的意见或建议..." rows={4} />
          </Form.Item>
          
          <Form.Item 
            name="create_process" 
            valuePropName="checked"
          >
            <Checkbox>使用当前模板创建工艺</Checkbox>
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 流程图对话框 */}
      <ProcessFlowChart 
        templateId={selectedTemplateId}
        isOpen={flowChartVisible}
        onClose={handleCloseFlowChart}
      />
      
      <style>{`
        .intelligent-recommendation {
          padding: 16px;
          height: 100%;
          display: flex;
          flex-direction: column;
        }
        
        .page-header {
          margin-bottom: 24px;
        }
        
        .tab-container {
          border-bottom: 1px solid #e8e8e8;
          margin-bottom: 16px;
        }
        
        .tabs {
          display: flex;
          flex-direction: row;
        }
        
        .tab-item {
          padding: 12px 16px;
          margin-right: 24px;
          font-size: 16px;
          cursor: pointer;
          position: relative;
        }
        
        .tab-item.active {
          color: #1890ff;
          font-weight: 500;
        }
        
        .tab-item.active:after {
          content: "";
          position: absolute;
          left: 0;
          bottom: -1px;
          width: 100%;
          height: 2px;
          background-color: #1890ff;
        }
        
        .action-bar {
          margin: 16px 0;
          display: flex;
          justify-content: flex-start;
        }
        
        .content-body {
          flex: 1;
          overflow-y: auto;
        }
        
        .model-card {
          height: 100%;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
          transition: all 0.3s;
        }
        
        .model-card:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 16px rgba(0, 0, 0, 0.12);
        }
        
        .model-card-content {
          display: flex;
          flex-direction: column;
          align-items: center;
        }
        
        .model-card-icon {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 150px;
          width: 100%;
          margin-bottom: 16px;
          color: #1890ff;
        }
        
        .pulsing-icon {
          animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
          0% {
            transform: scale(1);
            opacity: 1;
          }
          50% {
            transform: scale(1.1);
            opacity: 0.8;
          }
          100% {
            transform: scale(1);
            opacity: 1;
          }
        }
        
        .model-card-info {
          width: 100%;
        }
        
        .info-item {
          display: flex;
          margin-bottom: 8px;
        }
        
        .info-label {
          width: 90px;
          color: #666;
          font-size: 14px;
          flex-shrink: 0;
        }
        
        .info-value {
          flex: 1;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        
        .loading-container {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 300px;
        }
        
        .loading-container p {
          margin-top: 16px;
          font-size: 14px;
          color: #666;
        }
        
        .empty-data {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 300px;
          color: #999;
        }
        
        .empty-data p {
          margin-bottom: 16px;
        }
        
        .template-card {
          margin-bottom: 16px;
          border: 1px solid #e8e8e8;
          background-color: #f0f7ff;
        }
        
        .template-card-selected {
          border: 2px solid #1890ff;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
          background-color: #e6f7ff;
        }
        
        .template-card .ant-card-body {
          padding: 16px;
        }
        
        .template-selection-section {
          background-color: #f9f9f9;
          padding: 16px;
          border-radius: 4px;
          margin-bottom: 20px;
        }
        
        .feature-match-list {
          margin-top: 10px;
          padding-left: 20px;
        }
        
        .feature-match-item {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
        }
        
        .match-score {
          font-weight: bold;
          color: #1890ff;
        }
        
        .high-match {
          color: #52c41a;
        }
        
        .medium-match {
          color: #faad14;
        }
        
        .low-match {
          color: #f5222d;
        }
        
        /* 新增可视化样式 */
        .recommendation-visualization {
          padding: 10px;
        }
        
        .section-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 15px;
          color: #333;
          border-left: 4px solid #1890ff;
          padding-left: 10px;
        }
        
        .gauge-section {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding-bottom: 20px;
        }
        
        .gauge-container {
          width: 300px;
          height: 180px;
          position: relative;
        }
        
        .chart-section {
          margin: 20px 0;
        }
        
        .radar-container, .bar-container {
          height: 350px;
          position: relative;
          padding: 10px;
          background: #fafafa;
          border-radius: 4px;
        }
        
        .tag-cloud {
          background: #fafafa;
          padding: 10px;
          border-radius: 4px;
          min-height: 100px;
        }
        
        .template-selection-section {
          margin-top: 20px;
          margin-bottom: 20px;
          background: #f9f9f9;
          padding: 15px;
          border-radius: 4px;
          border: 1px solid #f0f0f0;
        }
        
        .template-card {
          transition: all 0.3s;
          cursor: pointer;
          height: 100%;
        }
        
        .template-card-selected {
          border: 2px solid #1890ff;
          box-shadow: 0 0 10px rgba(24, 144, 255, 0.5);
          transition: all 0.3s;
          cursor: pointer;
          height: 100%;
          background-color: rgba(24, 144, 255, 0.05);
        }
        
        .template-card:hover, .template-card-selected:hover {
          transform: translateY(-3px);
          box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .template-hint {
          font-size: 14px;
          color: #666;
          margin-bottom: 15px;
          text-align: center;
        }

        .template-card .ant-card-head-extra {
          display: flex;
          align-items: center;
        }
        
        .template-card-selected {
          border: 2px solid #1890ff;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
        }

        .template-card-actions {
          display: flex;
          gap: 8px;
          flex-wrap: wrap;
          justify-content: flex-end;
          margin-top: 12px;
        }

        .template-card-content {
          display: flex;
          flex-direction: column;
          gap: 8px;
          margin-top: 16px;
          border-top: 1px solid #f0f0f0;
          padding-top: 16px;
        }

        .template-card-header {
          display: flex;
          flex-direction: column;
        }

        .template-card-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
          margin-bottom: 8px;
          line-height: 1.4;
          word-break: break-word;
        }

        .template-card-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .template-card-label {
          color: #666;
          font-size: 14px;
        }

        .template-card-value {
          font-weight: 500;
          color: #333;
        }

        .template-card .ant-card-head {
          min-height: auto;
          padding: 0 12px;
        }

        .template-card .ant-card-head-title {
          padding: 12px 0;
          font-size: 15px;
          white-space: normal;
          word-break: break-word;
        }

        .template-card .ant-card-extra {
          padding: 8px 0;
        }

        .template-card .ant-card-body {
          padding: 16px;
        }

        .section-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 15px;
          color: #333;
          border-left: 4px solid #1890ff;
          padding-left: 10px;
        }

        .template-hint {
          font-size: 13px;
          color: #666;
          margin-bottom: 16px;
        }

        .gauge-section {
          margin-bottom: 20px;
        }

        .chart-section {
          margin: 20px 0;
        }

        /* 移动端响应式样式 */
        @media (max-width: 768px) {
          .template-card .ant-card-head-title {
            font-size: 14px;
            padding: 10px 0;
          }
          
          .template-card .ant-card-body {
            padding: 12px;
          }
          
          .section-title {
            font-size: 15px;
            margin-bottom: 12px;
          }
          
          .template-hint {
            font-size: 12px;
            margin-bottom: 12px;
          }
          
          .gauge-section {
            margin-bottom: 15px;
          }
          
          .chart-section {
            margin: 15px 0;
          }
          
          .radar-container, .bar-container {
            height: auto;
            max-height: 250px;
            margin-bottom: 20px;
          }
          
          .recommendation-visualization {
            padding: 5px;
          }

          .template-card-title {
            font-size: 15px;
            margin-bottom: 6px;
          }
          
          .template-card-content {
            margin-top: 12px;
            padding-top: 12px;
          }
          
          .template-card-actions {
            margin-top: 8px;
          }
        }
      `}</style>
    </div>
  );
};

export default IntelligentRecommendation;